package com.example.navigation.viewModel

import android.content.Context
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.navigation.api.ResponseData
import com.example.navigation.api.login.LoginApi
import com.example.navigation.api.login.LoginRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Created with IntelliJ IDEA.
 * @Author: Liao Run
 * @Date: 2024-06-08 10:20
 * @Description:
 **/
@HiltViewModel
class LoginViewModel @Inject constructor(
    private val loginRepository: LoginRepository,
    @ApplicationContext val context: Context
) :
    ViewModel() {

    var loginRes: MutableStateFlow<ResponseData<LoginApi.UserInfo>> =
        MutableStateFlow(value = ResponseData(0, "", null))

    fun login(loginParams: LoginApi.LoginParams) {
        viewModelScope.launch {
            val responseData = try {
                loginRepository.login(loginParams)
            } catch (e: Exception) {
                Toast.makeText(context, "网络超时", Toast.LENGTH_SHORT).show()
                return@launch
            }
            loginRes.emit(responseData)
        }
    }
}